package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 *
 * @author 孤风雪影
 * @date 2021/1/16
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登录成功回调
     * @param code
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        //1.根据用户授权返回的code换取access_token
        Map<String, String> querys = new HashMap<>();
        querys.put("client_id", "3007995822");
        querys.put("client_secret", "07c1b41d81c069e5479d0751806d02e3");
        querys.put("grant_type", "authorization_code");
        querys.put("redirect_uri", "http://auth.shopifymall.cn/oauth2.0/weibo/success");
        querys.put("code", code);

        //TODO 此处有点小Bug,单步调试会显示 400 BadRequest,直接运行没问题,以后可以换成HuTool工具发请求
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), querys, new HashMap<>());

        //2.处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了accessToken,封装在SocialUser里面
            String jsonString = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(jsonString, SocialUser.class);

            //社交登录或者注册，第一次就自动注册，第二次就直接登录
            R r = memberFeignService.oauth2Login(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo loginUser = r.getData(new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功:用户信息: {}", loginUser.toString());
                session.setAttribute(AuthServerConstant.LOGIN_USER, loginUser);
                return "redirect:http://mall.shopifymall.cn";

            } else {
                return "redirect:http://auth.shopifymall.cn/login.html";
            }

        } else {
            return "redirect:http://auth.shopifymall.cn/login.html";
        }

    }
}
